import time

db_tables = {
	
}

class SessionManagerBackend ( object ):
	def __init__ ( self, dbm, table_name ):
		super ( SessionManagerBackend, self ).__init__()
		self._dbm = dbm
		self._table_name = table_name

		self._dbm.table_add ( self._table_name, (
			( "id", "INT PRIMARY KEY NOT NULL AUTO_INCREMENT" ),
			( "sess_id", "VARCHAR(32)" ),
			( "last_mod_date", "INT" ),
			( "sess_data", "TEXT" ) ),

		#indexes
			( ( "sess_id", "UNIQUE" ), )
		)


	def check ( self ):
		return self._dbm.exists ( self._table_name )


	def install ( self ):
		self._dbm.table_create ( self._table_name )


	def drop ( self ):
		self._dbm.table_drop ( self._table_name )


	def add_session ( self, sess_id ):
		self._dbm.insert ( self._table_name, { "sess_id": sess_id, "last_mod_date": int(time.time()) } )

		
	def get_session ( self, sess_id ):
		r = self._dbm.single_row ( self._table_name, "*", "sess_id = '%s'" % sess_id )
		if not r: return None
		mod_date = r.get ( "sess_mod_date", int(time.time()) )
		r = r.get("sess_data")
		if not r: return None
		return self._dbm.unpickle ( r ), mod_date


	def del_session ( self, sess_id ):
		self._dbm.delete ( self._table_name, "sess_id = '%s'" % sess_id )


	def list_sessions ( self ):
		ret = self._dbm.select ( self._table_name, "*" )
		if ret:
			rs = ret.fetchall()
			ret.close()
		else:
			rs = []
		retval = [ ( r.get("sess_id", ""), r.get("last_mod_date", int(time.time())), self._dbm.unpickle ( r.get ( "sess_data", "" ) ) )
				for r in rs ]
		return retval


	def del_old_sessions ( self, time_limit ):
		now = int(time.time())
		exp_time = now - time_limit
		self._dbm.delete ( self._table_name, "last_mod_date < %d" % exp_time )


	def save_session ( self, sess_id, sess_data ):
		self._dbm.update ( self._table_name, { "last_mod_date": int(time.time()), "sess_data": self._dbm.pickle(sess_data) }, "sess_id = '%s'" % sess_id )


	def get_unique_id ( self ):
		return int ( self._dbm.count ( self._table_name, "*" ) )


# TEST
if __name__ == '__main__':
	from os3.dbm.dbmanager import DBManager
	dbm = DBManager ( DBManager.DBM_TYPE_MYSQL )
	dbm.set_prefix ( 'wa' )
	dbm.connect ( db = 'aspes', user = 'root', host = 'localhost' )

	smb = SessionManagerBackend ( dbm, 'session_manager' )

	#check
	print "check: %s" % smb.check()
	smb.install()
	print "check: %s" % smb.check()

		
